import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *


def print_with_time(*args, **kwargs):
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)








def On_SelectPage_Goto_OldVersion(driver:WebDriver):
    """切换页面选择页面到旧版本页面。

    Args:
        driver (WebDriver): WebDriver 实例对象  
    """
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,"//span[text()='返回旧版']")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
            
        try:
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[text()='已开通类目']")))
        except TimeoutException:
            print_with_time(f"提示 : 切换版本失败!请检查!")
        
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [返回旧版] 元素!应该当前界面就属于 旧版界面!")
        return




def On_SelectPage_Select_FirstCategory(driver:WebDriver,Cate_Name:str):
    """选择第一个类目.

    Args:
        driver (WebDriver): WebDriver 实例对象
        Cate_Name (str): 要选择的一级类目名称
    """
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'catItem')]//span[text()='{Cate_Name}']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        try:
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//input[@placeholder='搜索二级类目']")))
        except TimeoutException:
            print_with_time(f"提示 : 选择一级类目失败!没有出现二级类目菜单!请检查!")
        
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [{Cate_Name}] 元素!")




def On_SelectPage_Select_SecondCategory(driver:WebDriver,Cate_Name:str):
    """选择第二个类目.

    Args:
        driver (WebDriver): WebDriver 实例对象
        Cate_Name (str): 要选择的二级类目名称
    """
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//span[text()='{Cate_Name}']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        try:
            WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//button[@disabled]/span[text()='下一步']")))
        except TimeoutException:
            print_with_time(f"提示 : 选择二级类目失败!当前无法点击 [下一步] 按钮!请检查!")

        
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [{Cate_Name}] 元素!")





def Goto_Parameter_Input(driver:WebDriver):
    """从类目选择页面进入参数填写页面.

    Args:
        driver (WebDriver): WebDriver 实例对象
    """
    try:
        element = WebDriverWait(driver=driver,timeout=10).until(expected_conditions.presence_of_element_located((By.XPATH,f"//button[@disabled]/span[text()='下一步']")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [下一步] 按钮,无法进入参数填写页面!")





def UploadMainImage(driver: WebDriver, image_path: str) -> None:
    """上传主图。

    Args:
        driver (WebDriver): WebDriver 实例
        image_path (str): 图片文件的路径
    """
    try:
        upload_element = WebDriverWait(driver=driver, timeout=10).until(
            expected_conditions.presence_of_element_located((By.XPATH, "//input[@type='file']"))
        )
        upload_element.send_keys(image_path)
    except TimeoutException:
        print_with_time(f"提示 : 没有找到上传主图的输入框!")



def Open_SelectPage(driver:WebDriver):
    """打开选择类目的页面对话框.

    Args:
        driver (WebDriver): WebDriver 实例对象
    """
    def _InputTitle():
        """内部函数,输入标题.
        用来配合自动选择类目的使用的,设置的是固定值.

        Args:
            driver (WebDriver): WebDriver 实例对象
        """
        # 查找元素 【选择页面的标题输入框】
        _startTime = datetime.datetime.now()
        _seconds = 10
        _element_title_input : WebElement = None
        _element_title_inputXpathValue = "//input[@id='pg-title-input']"
        while _startTime + datetime.timedelta(seconds=_seconds) > datetime.datetime.now():
            try:
                # _element_title_inputXpathValue = str()
                _element_title_input = driver.find_element(by=By.XPATH,value=_element_title_inputXpathValue)
                break
            except NoSuchElementException as e:
                continue
            
        if _element_title_input:
            print("Element found!")
            print(_element_title_input)
        else:
            print("Element not found within the specified time!")
            
        
        
        
        _element : WebElement = _element_title_input
        _scrollElement : WebElement = _element
        _startTime = datetime.datetime.now()
        _seconds = 5
        _elementAttribute = "value"
        _elementAttribute_value = "卫衣"
        try:
            driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",_scrollElement)
            try:
                _element.click()
            except (ElementClickInterceptedException, ElementNotInteractableException):
                driver.execute_script("arguments[0].click();", _element)
        except:
            print("Unable To Execute Click To Focus!")
        
        if _element.get_attribute(_elementAttribute) != _elementAttribute_value:
            while _startTime + datetime.timedelta(seconds=_seconds) > datetime.datetime.now():
                _element.send_keys(Keys.BACKSPACE*20)
                if _element.get_attribute(_elementAttribute) == "":
                    break
            _element.send_keys(_elementAttribute_value)
            
            
            driver.find_element(by=By.XPATH,value="//*[text()='商品标题']").click()
            time.sleep(5)
    
    
    def _OpenRole():
        """内部函数,打开角色选择框.
        """
        # 查找元素 【更多推荐】
        for _ in range(2):
            _startTime = datetime.datetime.now()
            _seconds = 10
            _element : WebElement = None
            _elementXpathValue = "//span[text()='更多推荐']"
            while _startTime + datetime.timedelta(seconds=_seconds) > datetime.datetime.now():
                try:
                    _element = driver.find_element(by=By.XPATH,value=_elementXpathValue)
                    _element.click()
                    break
                except NoSuchElementException as e:
                    continue
                
            if _element:
                
                print("Element found!")
                print(_element)
            else:
                print("Element not found within the specified time!")

        
        # 查找元素 【手动查找】
        _startTime = datetime.datetime.now()
        _seconds = 10
        _element_Span_手动查找 : WebElement = None
        _element_Span_手动查找XpathValue = "//span[text()='手动选择']"
        while _startTime + datetime.timedelta(seconds=_seconds) > datetime.datetime.now():
            try:
                # _element_Span_手动查找XpathValue = str()
                _element_Span_手动查找 = driver.find_element(by=By.XPATH,value=_element_Span_手动查找XpathValue)
                break
            except NoSuchElementException as e:
                continue
            
        if _element_Span_手动查找:
            print("Element found!")
            print(_element_Span_手动查找)
            _element_Span_手动查找.click()
        else:
            print("Element not found within the specified time!")
    
    
    
    
    
    
    # 1.输入标题
    _InputTitle()
    
    # 2.打开对话框
    _OpenRole()